<template>
  <div class="bingewatch-container">
    <!-- 顶部导航区域：包含两个切换标签和编辑按钮 -->
    <div class="nav-header">
      <div class="tab-container">
        <template v-for="tab in tabs" :key="tab.value">
          <div
            @click="activeTab = tab.value"
            :class="{
              'active-tab': activeTab === tab.value,
              'inactive-tab': activeTab !== tab.value
            }"
            class="tab-item"
          >
            <span class="tab-text">{{ tab.label }}</span>
          </div>
        </template>
      </div>
      <button class="edit-button">
        <i class="fas fa-edit"></i>
      </button>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 加载状态 - 替换为骨架屏 -->
      <div v-if="loading">
        <!-- 我的在追骨架屏 -->
        <div v-if="activeTab === 'following'" class="tv-grid">
          <div v-for="i in 6" :key="i" class="tv-card skeleton-card">
            <div class="tv-image skeleton-image"></div>
            <div class="p-2">
              <div class="skeleton-text-short"></div>
              <div class="skeleton-text-mini mt-1"></div>
            </div>
          </div>
        </div>

        <!-- 浏览记录骨架屏 -->
        <div v-else class="history-list">
          <div v-for="i in 5" :key="i" class="history-item skeleton-history-item">
            <div class="history-content">
              <div class="history-image skeleton-history-image"></div>
              <div class="history-info">
                <div class="skeleton-text-medium"></div>
                <div class="skeleton-text-small"></div>
              </div>
            </div>
            <div class="skeleton-star-button"></div>
          </div>
        </div>
      </div>

      <!-- 我的在追 -->
      <div v-else-if="activeTab === 'following'">
        <div v-if="followingList.length !== 0" class="tv-grid">
          <!-- 剧集卡片 -->
          <div class="tv-card" v-for="item in followingList" :key="item.id" @click="handleDramaClick(item)">
            <div class="tv-image">
              <img :src="item.cover" :alt="item.title" />
              <span class="new-tag" v-if="item.isNew">新剧</span>
              <span class="episode-count">全{{ item.totalEpisodes }}集</span>
            </div>
            <div class="tv-info">
              <div class="tv-title">{{ item.title }}</div>
              <div class="watch-progress">观看至{{ item.currentWatchEpisode || item.lastWatchEpisode || 1 }}集</div>
            </div>
          </div>
        </div>
        <div v-else class="empty-state">
          <i class="far fa-sad-tear empty-icon"></i>
          <p class="empty-text">您还没有追剧，去首页发现好剧吧</p>
        </div>
      </div>

      <!-- 浏览记录 -->
      <div v-else-if="activeTab === 'history'">
        <div v-if="historyList.length !== 0" class="history-list">
          <div v-for="item in historyList" :key="item.id" class="history-item">
            <div class="history-content" @click="handleDramaClick(item)">
              <div class="history-image">
                <img :src="item.cover" class="history-img" alt="剧集" />
              </div>
              <div class="history-info">
                <h3 class="history-title">{{ item.title }}</h3>
                <p class="history-progress">观看至{{ item.currentWatchEpisode || item.lastWatchEpisode || 1 }}集</p>
              </div>
            </div>
            <button @click.stop="toggleStarStatus(item)" :class="{ starred: item.isStarred }" class="star-button">
              <i :class="item.isStarred ? 'fas fa-star' : 'far fa-star'" class="star-icon"></i>
              <p class="star-text">
                {{ item.isStarred ? '已追剧' : '追剧' }}
              </p>
            </button>
          </div>
        </div>
        <div v-else class="empty-state">
          <i class="far fa-clock empty-icon"></i>
          <p class="empty-text">暂无浏览记录</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { reqMyFollowingList, reqBrowsingHistory, toggleDramaFollow } from '@/apis/video'

// 路由实例
const router = useRouter()

// 当前激活的标签页（'following'我的在追/'history'浏览记录）
const activeTab = ref('following')

// 我的在追剧集列表数据
const followingList = ref([])
// 浏览记录列表数据
const historyList = ref([])

// 加载状态标识（控制加载提示显示）
const loading = ref(true)

// 标签页配置
const tabs = [
  { value: 'following', label: '我的在追' },
  { value: 'history', label: '浏览记录' }
]

// 获取追剧页面数据的核心方法
const fetchBingewatchData = async () => {
  try {
    loading.value = true

    // 添加短暂延迟以确保骨架屏显示效果
    await new Promise((resolve) => setTimeout(resolve, 300))

    if (activeTab.value === 'following') {
      const { data: followings } = await reqMyFollowingList()
      followingList.value = followings?.list || []
    } else {
      const { data: historys } = await reqBrowsingHistory()
      historyList.value = historys?.list || []
    }
  } catch (error) {
    console.error('获取追剧数据失败:', error)
    showToast('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理剧集点击
const handleDramaClick = (drama) => {
  console.log('点击追剧页面剧集:', drama.title, 'ID:', drama.id, '当前集数:', drama.currentEpisode)

  // 计算要跳转的集数索引（数组从0开始）
  const episodeIndex = drama.currentEpisode ? drama.currentEpisode - 1 : 0

  // 如果剧集有videos数据，直接传递
  if (drama.videos && drama.videos.length > 0) {
    router.push({
      name: 'Player',
      params: { dramaId: drama.id }
    })
  } else {
    // 否则只传递dramaId和episodeIndex，让播放页面自己获取数据
    router.push({
      name: 'Player',
      params: { dramaId: drama.id }
    })
  }
}

// 切换追剧状态（仅浏览记录部分）
// 切换浏览记录中剧集的追剧状态（操作本地数据+显示提示）
const toggleStarStatus = async (item) => {
  // 切换当前状态
  item.isStarred = !item.isStarred

  const dramaId = item.id
  const action = item.isStarred ? 'follow' : 'unfollow'
  // 这里调用接口更新服务器状态
  const response = await toggleDramaFollow(dramaId, action)
  console.log('切换追剧状态响应:', response)

  // 显示提示消息
  if (item.isStarred) {
    showToast(`已添加《${item.title}》到追剧列表`)
  } else {
    showToast(`已取消追剧《${item.title}》`)
  }
}

// 监听标签页变化，重新加载对应数据
watch(activeTab, () => {
  fetchBingewatchData()
})

onMounted(() => {
  fetchBingewatchData()
})
</script>

<style scoped lang="scss">
.bingewatch-container {
  width: 100%;
  min-height: 100vh;
  position: relative;
  padding-top: 80px; // 添加顶部内边距，为固定导航腾出空间
}

.nav-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem 0;
  position: fixed; // 改为固定定位
  top: 0;
  left: 0;
  right: 0;
  width: 100%;
  background-color: #fff; // 添加背景色
  z-index: 100; // 确保在其他元素上方
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1); // 添加阴影效果

  .tab-container {
    display: flex;
    gap: 2rem;
  }

  .tab-item {
    cursor: pointer;

    &.active-tab {
      border-bottom: 2px solid #ef4444;
      padding-bottom: 0.25rem;
    }

    &.inactive-tab {
      color: #9ca3af;
    }
  }

  .tab-text {
    font-size: 1.125rem;
    font-weight: 500;
  }

  .edit-button {
    position: absolute;
    right: 1rem;
    color: #fff;
  }
}

.content-area {
  padding: 0 1rem 5rem;
}

.tv-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;

  .tv-card {
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .tv-image {
    position: relative;
    width: 100%;
    padding-top: 140%; /* 保持宽高比 */
    overflow: hidden;

    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .new-tag {
      position: absolute;
      top: 6px;
      right: 6px;
      background-color: #4cd964;
      color: white;
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 3px;
      font-weight: bold;
    }

    .episode-count {
      position: absolute;
      bottom: 6px;
      right: 6px;
      background-color: rgba(0, 0, 0, 0.6);
      color: white;
      font-size: 11px;
      padding: 1px 5px;
      border-radius: 3px;
    }
  }

  .tv-info {
    padding: 8px 6px 6px;

    .tv-title {
      font-size: 13px;
      color: #333;
      font-weight: 500;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: 3px;
    }

    .watch-progress {
      font-size: 11px;
      color: #999;
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  height: 30vh;

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(0, 0, 0, 0.1);
    border-top-color: #f97316;
    border-radius: 50%;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 1rem;
  }

  .loading-text {
    color: #666;
    font-size: 1rem;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  color: #9ca3af;
  height: 30vh;

  .empty-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
    color: #d1d5db;
  }

  .empty-text {
    font-size: 1rem;
  }
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .history-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .history-content {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.history-image {
  width: 64px;
  height: 80px;
  background-color: #1f2937;
  border-radius: 8px;
  margin-right: 12px;
  overflow: hidden;
  transition: opacity 0.3s;

  &:hover {
    opacity: 0.8;
  }

  .history-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.history-info {
  display: flex;
  flex-direction: column;

  .history-title {
    font-weight: 500;
    margin-bottom: 4px;
    color: #333;
  }

  .history-progress {
    color: #9ca3af;
    font-size: 14px;
  }
}

.star-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
  width: 50px;

  &.starred {
    color: #f97316;
  }

  .star-icon {
    font-size: 20px;
  }

  .star-text {
    font-size: 12px;
    margin-top: 4px;
  }
}

.toast-message {
  position: fixed;
  bottom: 5rem;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  z-index: 50;
}

/* 骨架屏样式 */
.skeleton-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.skeleton-image {
  position: relative;
  width: 100%;
  padding-top: 140%;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-text-short {
  height: 16px;
  width: 80%;
  border-radius: 4px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-text-mini {
  height: 12px;
  width: 50%;
  margin-top: 5px;
  border-radius: 4px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-history-item {
  padding: 10px;
  border-radius: 8px;
  background-color: white;
}

.skeleton-history-image {
  width: 64px;
  height: 80px;
  border-radius: 8px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-text-medium {
  height: 18px;
  width: 120px;
  border-radius: 4px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  margin-bottom: 8px;
}

.skeleton-text-small {
  height: 14px;
  width: 80px;
  border-radius: 4px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-star-button {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}
</style>
